using UnityEngine;
using GameCore; // AssetsManager & GameObjectPool
using System.Collections;

public class Monster : MonoBehaviour
{
    public float detectRadius = 2f;
    public int hitValue = 10;
    public int healthMax = 100;
    public int scoreOnDeath = 50;
    public float moveSpeed = 3.5f;
    public float attackTime = 1f;

    public string[] lootKeys;

    int healthCurrent;
    Transform targetTrans;
    Animator animator;
    bool attackingFlag;
    Vector3 initialScale;

    public void Init()
    {
        healthCurrent = healthMax;
        attackingFlag = false;

        if (animator == null)
            animator = GetComponent<Animator>();

        animator.cullingMode = AnimatorCullingMode.AlwaysAnimate;
        animator.SetBool("Attack", false);

        var sr = GetComponent<SpriteRenderer>();
        if (sr != null)
        {
            sr.enabled = true;
            sr.sortingLayerName = "Monster";
            sr.sortingOrder = 10;
        }

        var col = GetComponent<Collider2D>();
        if (col != null)
            col.enabled = true;

        if (targetTrans == null)
        {
            var playerObj = GameObject.FindWithTag("Player");
            if (playerObj != null)
                targetTrans = playerObj.transform;
        }
    }

    void Start()
    {
        healthCurrent = healthMax;
        var playerObj = GameObject.FindWithTag("Player");
        if (playerObj != null)
            targetTrans = playerObj.transform;

        animator = GetComponent<Animator>();
        initialScale = transform.localScale;
    }

    void Update()
    {
        if (healthCurrent <= 0 || attackingFlag || targetTrans == null)
            return;

        var sr = GetComponent<SpriteRenderer>();
        if (sr != null)
        {
            sr.enabled = true;
            Color c = sr.color;
            if (c.a < 1f)
                c.a = 1f;
            sr.color = c;
        }

        Vector3 newScale = initialScale;
        float dirX = (targetTrans.position.x > transform.position.x)
            ? Mathf.Abs(initialScale.x)
            : -Mathf.Abs(initialScale.x);
        newScale.x = dirX;
        transform.localScale = newScale;

        float dist = Vector2.Distance(transform.position, targetTrans.position);
        if (dist <= detectRadius)
            StartCoroutine(DoAttack());
        else
            MoveTowards();
    }

    void MoveTowards()
    {
        Vector2 next = Vector2.MoveTowards(
            transform.position,
            targetTrans.position,
            moveSpeed * Time.deltaTime
        );
        transform.position = new Vector3(next.x, next.y, transform.position.z);
    }

    IEnumerator DoAttack()
    {
        attackingFlag = true;
        animator.SetBool("Attack", true);
        yield return new WaitForSeconds(attackTime);

        if (Vector2.Distance(transform.position, targetTrans.position) <= detectRadius)
        {
            var pc = targetTrans.GetComponent<PlayerController2D>();
            if (pc != null)
                pc.TakeDamage(hitValue);
        }

        animator.SetBool("Attack", false);
        attackingFlag = false;
    }

    public void TakeDamage(int value)
    {
        if (healthCurrent <= 0)
            return;

        healthCurrent -= value;
        if (healthCurrent <= 0)
            HandleDeath();
    }

    void HandleDeath()
    {
        if (lootKeys != null && lootKeys.Length > 0)
        {
            int idx = Random.Range(0, lootKeys.Length);
            string key = lootKeys[idx];
            string path = $"Assets/Res/Prefabs/{key}.prefab";

            AssetsManager.Instance.LoadGameObject(path, obj =>
            {
                obj.transform.position = transform.position;
                obj.transform.rotation = Quaternion.identity;
                obj.GetComponent<Monster>()?.Init();
            });
        }

        GameObjectPool.Instane.PushInPool(gameObject);
        gameObject.SetActive(false);
    }

    void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.red;
        Gizmos.DrawWireSphere(transform.position, detectRadius);
    }
}
